#coding:utf-8
#from make_mime_type import upload_file,deal_attach_file, make_MIMEMultipart
from kgdata import Kgdata
from settings import DEBUG

from google.appengine.api import users
from google.appengine.api import mail

def format_from_gdata(email, password, sheet_filename, sheet_tb_name):
    '''
    @param: 
      -- email: 登录google邮箱
      -- password：Google 密码
      -- sheet_filename ：要读的电子表格文件名
      -- sheet_tb_name ：文件内表名称形如 sheet1
    @return：
        tuple
        成功：(True, 返回一个二维的list)
        失败：(False，与出错信息str)
    '''
    if isinstance(sheet_filename, unicode):
        sheet_filename = sheet_filename.encode('utf8')
    if isinstance(sheet_tb_name, unicode):
        sheet_tb_name = sheet_tb_name.encode('utf8')
    
    try:
        kgdata = Kgdata(email, password)
        kgdata.set_Spreadsheet_File_Key(sheet_filename)
        kgdata.set_wksht_id(sheet_tb_name)
        arrlstResult = kgdata.read_WorkSheet_by_Cells()
        return True, arrlstResult
    except Kgdata.FileNotFile, e:
        return False, "文件不到:'%s'！建议尽量不要使用中文文件名。< br> raise:%s" % (sheet_filename, e)
    except Kgdata.WorkSheetNotFind, e:
        return False, '表"%s"找不到，！建议尽量不要使用中文表名。< br> nraise:%s' % (sheet_tb_name, e)
    except Exception, e:
        if DEBUG: raise e
        print e, __file__
        return False, '%s 找不到该表！建议尽量不要使用中文文件名\表名(大小写敏感)。%s' % (sheet_tb_name, e)    
#end format_from_gdata()

def format_from_txet(txtToMails):
    '''
    @param txtToMails: 可转成二维文本的txt
     返回一个二维的list，与format_from_gdata()返回的格式应一样
    @return：
        tuple
        成功：(True, 返回一个二维的list)
        失败：(False，与出错信息str)
    '''
    if not txtToMails:
        return False, '收件列表为空'
    if isinstance(txtToMails, unicode):
        txtToMails = txtToMails.encode('utf8')
    arrlist2Mail = []
    for line in txtToMails.strip().split('\n'):
        if line.__len__()  <= 2: # 因为一定有邮箱地址，长度不可能小于2
            pass
        else:
            l = line.split('|') #使用定义的特别称号分隔数据
            if l.__len__() == 1:
                l = line.split('\t') #或使用'tab'键
            if l.__len__() == 1:
                l = line.split(',') #或使用英文','
            arrlist2Mail.append(l)
    return True, arrlist2Mail
#end format_from_locad()

def send_multi_mail(replyTo, arrMailList, mailIndex, listMacro, \
                     mailTitle, mailContent, isSendMyself = False):
    '''
    @return: 
        (sendSucceedMailList, sendFailedMailList, lastMailContent)
    AuthInfo: 字典，包含server,user,password
    arrMailList:一个二维list，由format_from_gdata 或 format_from_locad 构建
    mailIndex：邮箱地址所在列
    MacroList: 自定义宏，使用英文逗号(',')号隔开.如：$Name$, $Mail$, $Job$
    MailTitle: 邮件标题，纯文件，可包含宏。
    MailContext：邮件内容，HTML文本，可包含宏。
    AttachFilePath：附件路径
    isSendMyself：是否发送给自己
    '''
    #以下四个返回值
    succeed = []   #成功发送邮件个数
    failed =  []   #失败个数
    if not isinstance(listMacro, list):
        listMacro = listMacro.strip().split(',')
    if isinstance(mailContent, unicode):
        mailContent = mailContent.encode('utf8')
    if isinstance(mailTitle, unicode):
        mailTitle = mailTitle.encode('utf8')
    
    for line in arrMailList:#一个二维list，
        assert line.__len__() > mailIndex, 'mail index must laster then line length.'
        assert isinstance(line, list) or isinstance(line, tuple), 'must array of list or tuple.'
        if not line:continue
        for macro in listMacro:
            nIndex = listMacro.index(macro)
            macro = macro.strip() #去两边空格
            if not macro:
                print "macro is emtpy!"
                continue
            if line.__len__() > nIndex:
                strTemp = line[nIndex].strip()
                if type(strTemp) is unicode: strTemp = strTemp.encode('utf8')
                title = mailTitle.replace(macro, strTemp)
                mailHtml = mailContent.replace(macro, strTemp)
            else:
                title = mailTitle.replace(macro, '')
                mailHtml = mailContent.replace(macro, '')

        # 发送邮件
        message = mail.EmailMessage()
        message.sender = users.get_current_user().email()
        message.reply_to = replyTo
        message.subject = title
        message.html = mailHtml
        try:
            if (isSendMyself):
                tolist = [line[mailIndex], replyTo]
                message.to = tolist
            else:
                message.to = line[mailIndex]
            message.send()
            succeed.append(line[mailIndex])
        except Exception, e:
            failed.append(line[mailIndex])
            print e
            # raise e
    return succeed, failed, mailHtml
#end Send_Group_Mail()

if __name__ == "__main__":
    pass